package com.citic.topview.system.util;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import com.alibaba.fastjson.JSON;
import com.citic.topview.common.security.Principal;
import com.citic.topview.common.system.entity.User;
import com.citic.topview.system.service.UserService;

import net.sf.json.JSONObject;

public class ShiroUtils {
	
	private static UserService userService = SpringContextHolder.getBean("userService", UserService.class);
	
    public static Subject getSubjct() {
        return SecurityUtils.getSubject();
    }
    
    public static Principal getPrincipal() {
    	Subject subject = getSubjct();
    	Object object = subject.getPrincipal();
    	
    	Principal principal = null;
    	if(object instanceof Principal) {
    		principal = (Principal) object;
    	} else if(object == null){
    		return null;
    	} else {
    		String json = JSON.toJSON(object).toString();
			JSONObject jsonObject = JSONObject.fromObject(json);//将json字符串转换为json对象
    		principal = new Principal(jsonObject.getLong("id"), jsonObject.getString("loginName"), jsonObject.getString("name"), jsonObject.getBoolean("mobileLogin"));
    	}

    	return principal;
    }
    
    public static Principal getPrincipal(Subject subject) {
    	Object object = subject.getPrincipal();
    	
    	Principal principal = null;
    	if(object instanceof Principal) {
    		principal = (Principal) object;
    	} else if(object == null){
    		return null;
    	} else {
    		String json = JSON.toJSON(object).toString();
    		JSONObject jsonObject = JSONObject.fromObject(json);//将json字符串转换为json对象
    		principal = new Principal(jsonObject.getLong("id"), jsonObject.getString("loginName"), jsonObject.getString("name"), jsonObject.getBoolean("mobileLogin"));
    	}
    	
    	return principal;
    }
    
    public static User getUser() {
    	if(getPrincipal() == null) {
    		return null;
    	}
    	return userService.get(getPrincipal().getId());
    }
    
    public static void logout() {
        getSubjct().logout();
    }
    
	public static Session getSession(){
		try{
			Subject subject = SecurityUtils.getSubject();
			Session session = subject.getSession(false);
			if (session == null){
				session = subject.getSession();
			}
			if (session != null){
				return session;
			}
		}catch (InvalidSessionException e){
			
		}
		return null;
	}
}
